import time,re
import pandas as pd
import redis
import pickle
import logging
import pywencai
import akshare as ak
import pandas as pd
import configparser
import datetime
from sqlalchemy import create_engine
import pymysql
import os
import traceback
from send_email import sendMessage
from 个股行业与概念涨幅分析 import get_brand_and_concept_rank

import easytrader


pymysql.install_as_MySQLdb()


log_format = "%(asctime)s - %(levelname)s - %(process)d - %(filename)s:%(lineno)d - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"  # 精确到秒
logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=date_format)

pid = os.getpid()
query_date = datetime.datetime.now().strftime('%Y%m%d')

# 日志文件路径
log_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'log/xueqiu.log')

# 创建一个 handler，用于写入日志文件
file_handler = logging.FileHandler(log_file_path)
file_handler.setFormatter(logging.Formatter(log_format, date_format))
# 添加 handler 到 logger
logging.getLogger().addHandler(file_handler)

# 初始化配置解析器
config = configparser.ConfigParser()

# 读取配置文件
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
config.read(current_dir+'/config.ini', encoding='utf-8')


# 获取Redis的配置信息
redis_host = config.get('Redis', 'host')
redis_port = config.getint('Redis', 'port')
redis_db = config.getint('Redis', 'db')
redis_password = config.get('Redis', 'password')
r = redis.Redis(host=redis_host, port=redis_port, db=redis_db, password=redis_password)

mysql_port = config.getint('mysql', 'port')
mysql_host = config.get('mysql', 'host')
mysql_db = config.get('mysql', 'db')
import urllib.parse
mysql_password = urllib.parse.quote(config.get('mysql', 'password'))
mysql_user = config.get('mysql', 'user')
db_url = f'mysql://{mysql_user}:{mysql_password}@{mysql_host}:{mysql_port}/{mysql_db}'

engine = create_engine(db_url,pool_size=20,max_overflow=20,pool_recycle=60)


if __name__ == "__main__":
    query_date = datetime.datetime.now().strftime('%Y%m%d')
    # query_date = datetime.datetime.now().strftime('%Y-%m-%d')

    user = easytrader.use('xq')
    user.prepare('xueqiu.json')
    print(user.position)

    pubsub = r.pubsub()
    # 订阅频道
    pubsub.psubscribe('stock_buy')

    # 监听订阅的频道
    try:
        logging.info("雪球监控进程启动")
        for message in pubsub.listen():
            # 检查消息类型
            if message['type'] == 'pmessage':
                user.prepare('xueqiu.json')

                code_bytes = message['data']
                code = code_bytes.decode('utf-8')  # 解码为UTF-8字符串
                user.adjust_weight(code, 10)
                logging.info(f"{code}买入成功")

    except KeyboardInterrupt:
        logging.info("停止监听")
    finally:
        # 关闭PubSub连接
        pubsub.close()






